package com.bzy.shiro.util;

import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

public class PasswordUtil {

	private static String algorithmName = "md5";
	private static int hashIterations = 2;


    /**
     * 生成盐
     * @return
     */
	public static String generateSalt() {
		RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
		String salt = randomNumberGenerator.nextBytes().toHex();
		return salt;
	}

    /**
     * 生成加密密码
     * @param username
     * @param password
     * @return
     */
	public static String encryptPassword(String username, String password) {
		String salt = generateSalt();
		String encryptPassword = new SimpleHash(algorithmName, password, ByteSource.Util.bytes(username + salt),
				hashIterations).toHex();
		return encryptPassword;
	}

	public static String encryptPassword(String username, String password, String salt) {
		String encryptPassword = new SimpleHash(algorithmName, password, ByteSource.Util.bytes(username + salt),
				hashIterations).toHex();
		return encryptPassword;
	}

    public static void main(String[] args) {
	    String salt = "f448952c618b24e0a86e1abed079194c";
        String password = encryptPassword("admin", "123456", salt);
        System.out.println(password);
    }
}
